/**
 * Created by oneminute on 8/12/14.
 */

var lz = require("../lib/utils/modules")();
var request = require("request");
var xmlParser = require("xml2json");
var util = require("util");
var moment = require("moment");
var async = require("async");

exports.get = function (_req, _res, _opts, _callback) {
    // 你需要给我返回 是否已经注册过 这个号码 如果注册过 我提示用户是否直接登录
    var phone = _opts.phone;
    lz.Logger.debug("/requestcode: ", phone);

    // 先判断手机号是否已经被注册过
    lz.ArangoDB.countObjectsByAQL(lz.Config.db.arango.aqls.GET_OBJECT_BY_PROPERTY, {
        "@collection": lz.Config.db.arango.users,
        prop: "loginPhone",
        value: phone
    }, function (_err, _count) {
        if (_err) {
            lz.Logger.error("/requestcode: 查询手机号是否已经被注册时发生错误。", _err);
            _callback(_err);
            return;
        }

        if (_count > 0) {
            lz.Logger.warn("/requestcode: 该手机号%s已经被注册。", phone);
            _callback(lz.Config.errors.getError(lz.Config.errors.REGISTER_USER_EXISTED));
            return;
        }

        // 再来作手机号是否已发送的验证
        var messageCode = new lz.MessageCode({phone: phone});
        messageCode.list({
            method: "byAQL",
            aql: lz.Config.db.arango.aqls.LIST_MESSAGE_CODE,
            params: {
                "@collection": lz.Config.db.arango.codes,
                phone: phone,
                type: "register"
            }
        }, function (_err, _messages) {
            if (_err) {
                lz.Logger.error("/requestcode: 查询%s的消息码时出现错误。", phone);
                _callback(_err);
                return;
            }
            lz.Logger.debug("/requestcode: 检索当前手机用户%s的验证码返回: ", phone, _messages);
            // 判断是否有_messages，如果有，则判断最近的一条是否已经过期。
            if (Array.isArray(_messages) && _messages.length > 0) {
                var sms = _messages[0];
                // 判断是否在重发间隔期内
                var sentTime = moment(sms.timestamp, lz.Config.datetimeFormatLong);
                var now = moment();
                var canResendTime = sentTime.add(moment.duration(lz.Config.sms.resendinterval * 1000));
                // 发送过于频繁
                if (now.isBefore(canResendTime)) {
                    _callback(lz.Config.errors.getError(lz.Config.errors.REQUEST_SMS_TOO_FREQUENT));
                    return;
                }
                lz.Logger.debug("/requestcode: 准备删除所有旧的验证码。");
                var tasks = [];
                _messages.forEach(function (_msg) {
                    tasks.push(function (_cb) {
                        _msg.delete(function () {
                            _cb(null);
                        });
                    });
                });
                async.series(tasks, function () {
                    lz.Logger.debug("/requestcode: 已经删除所有旧的验证码。");

                    sendSms();
                });
            } else {
                sendSms();
            }
        });
    });

    function sendSms() {
        // 生成新的验证码
        var code = parseInt(Math.random() * 900000) + 100000;
        var content = util.format(lz.Config.sms.templates.register, code);
        var url = util.format(lz.Config.sms.url, lz.Config.sms.account, lz.Config.sms.password, phone, content);
        lz.Logger.debug("/requestcode: 准备请求消息码。", url);
        request(url, function (_err, _res, _body) {
            /*
             <?xml version="1.0" encoding="utf-8"?>
             <SubmitResult xmlns="http://106.ihuyi.cn/">
             <code>2</code>
             <msg>提交成功</msg>
             <smsid>24226341</smsid>
             </SubmitResult>
             */
            if (!_err && _res.statusCode == 200) {
                var result = xmlParser.toJson(_body, {object: true}).SubmitResult;
                lz.Logger.debug("/requestcode: 收到短信平台的反馈信息: ", result);
                if (result.code == 2) {
                    var messageCode = new lz.MessageCode({
                        smsid: result.smsid,
                        phone: phone,
                        code: code
                    });

                    messageCode.save(function (_err, _code) {
                        if (_err) {
                            lz.Logger.error("/requestcode: 系统在保存验证码时发生错误。", _err);
                            _callback(_err);
                            return;
                        }

                        lz.Logger.debug("/requestcode: 生成验证码成功。", code);
                        _callback(null, _opts.user, {smsid: result.smsid});
                    });
                } else {
                    lz.Logger.error("/requestcode: 发送短信出现错误。", _err);
                    _callback(lz.Config.errors.getError(lz.Config.errors.REQUEST_SMS_ERROR, {msg: result.msg}));
                }
            } else {
                lz.Logger.error("/requestcode: 发送短信出现错误。", _err);
                _callback(lz.Config.errors.getError(lz.Config.errors.REQUEST_SMS_ERROR, _err));
            }
        });
    }
};
